package asf.core
{
	import asf.controllers.FrontController;
	import asf.resources.URLResources;
	
	import flash.display.LoaderInfo;
	import flash.utils.Proxy;
	import flash.utils.flash_proxy;
	
	dynamic public class ApplicationParameters extends Proxy
	{
		private var configXML:XML;
		private var _defaults:Object;
		private var loaderInfo:LoaderInfo;
		private var app:*;
		
		private var overrides:Object;
		
		public function ApplicationParameters( p_config:XML, p_loaderInfo:LoaderInfo, p_app:* )
		{
			_defaults = new Object( );
			overrides = new Object( );
			
			this.app = p_app;
			this.loaderInfo = p_loaderInfo;
			this.configXML = p_config;
		}
		
		public function setData( data:XML ):void
		{
			this.configXML = data;
		}
		
		override flash_proxy function callProperty( name:*, ...rest ):* 
		{
			throw new Error( "!WARNING! There is no method called: " + name + " in [ApplicationParameters]" );
			return null;
		}
		
		override flash_proxy function getProperty( name:* ):*
		{
			return getParam( name );
		}
		
		public function getParam( paramName:String ):*
		{
			if( ( configXML == null || !configXML.hasOwnProperty( "parameters" ) ) && !loaderInfo.parameters.hasOwnProperty( paramName ) )
			{
				return getParsedValue( overrides[ paramName ] ) || URLResources.getQueryStringParam( paramName ) || getParsedValue( defaults[ paramName ] );
			}
			else if( configXML != null )
			{
				return getParsedValue( overrides[ paramName ] ) || URLResources.getQueryStringParam( paramName ) || loaderInfo.parameters[ paramName ] || getParsedValue( configXML.parameters[ paramName ] ) || getParsedValue( defaults[ paramName ] );
			}
			else
			{
				return getParsedValue( overrides[ paramName ] ) || URLResources.getQueryStringParam( paramName ) || loaderInfo.parameters[ paramName ] || getParsedValue( defaults[ paramName ] );
			}
		}
		
		override flash_proxy function setProperty( name:*, value:* ):void
		{
			overrides[ name ] = value;
			
			FrontController.broadcastEvent( AppGlobalCommands.PARAMETER_CHANGED );
		}
		
		public function get defaults( ):Object
		{
			return _defaults;
		}
		
		private function getParsedValue( raw:String ):*
		{
			return ApplicationParser.parse( raw, configXML, app );
		}
	}
}